package cn._2dland.bots.jdo;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

import cn._2dland.bots.jdo.models.U115PickLog;

@SuppressWarnings("unchecked")
public class U115BotLogger {
	private U115BotLogger() {}

	public static void logPick(Long acctID, int pick){
		PersistenceManager pm = PMFactory.getPMFInstance().getPersistenceManager();
		Transaction trans = pm.currentTransaction();
		try {
			trans.begin();
			U115PickLog log = new U115PickLog(acctID, pick, System.currentTimeMillis());
			pm.makePersistent(log);
			trans.commit();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			if(trans.isActive())
				trans.rollback();
			if(pm != null)
				pm.close();
		}
	}

	/**
	 * 查询日志
	 * @param acctID
	 * @return
	 */
	public static List<U115PickLog> query(Long acctID){
		List<U115PickLog> logs = null;
		PersistenceManager pm = PMFactory.getPMFInstance().getPersistenceManager();
		try {
			Query q = pm.newQuery(U115PickLog.class);
			q.setFilter("accountID == " + acctID);
			logs = (List<U115PickLog>)q.execute();
		}
		catch (Exception e) {
			logs = null;
			e.printStackTrace();
		}
		finally {
			if(pm != null)
				pm.close();
		}
		return logs;
	}

	/**
	 * 查询一个时间段内的日志
	 * @param acctID
	 * @param beginTime
	 * @param endTime
	 * @return
	 */
	public static List<U115PickLog> query(Long acctID, long beginTime, long endTime){
		List<U115PickLog> logs = null;
		PersistenceManager pm = PMFactory.getPMFInstance().getPersistenceManager();
		try {
			Query q = pm.newQuery(U115PickLog.class);
			StringBuffer filter = new StringBuffer("accountID == " + acctID);
			if(beginTime >= 0)
				filter.append("and time >= " + beginTime);
			if(endTime >= 0)
				filter.append("and time <= " + endTime);
			q.setFilter(filter.toString());
			logs = (List<U115PickLog>)q.execute();
		}
		catch (Exception e) {
			logs = null;
			e.printStackTrace();
		}
		finally {
			if(pm != null)
				pm.close();
		}
		return logs;
	}
}
